package com.mall.huohuo.common.logback.encoder;

import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.PatternLayoutEncoderBase;
import com.mall.huohuo.trace.TraceUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author zycoding
 * @version AuthParam.java, v 0.1 2020-08-07 16:23 zycoding
 */

public class TracePatternLayoutEncoder extends PatternLayoutEncoderBase {
    @Override
    public void start() {
        TraceLayout traceLayout = new TraceLayout();
        traceLayout.setContext(this.context);
        traceLayout.setPattern(getPattern());
        traceLayout.setOutputPatternAsHeader(this.outputPatternAsHeader);
        traceLayout.start();
        this.layout = traceLayout;
    }

    public static class TraceLayout extends PatternLayout {
        @Override
        public String doLayout(ILoggingEvent event) {

            return "----> " + getTrace() + " ---    " + super.doLayout(event);
        }

        private String getTrace() {
            if (StringUtils.isEmpty(TraceUtils.getTrace())) {
                return TraceUtils.generateTrace();
            }
            return TraceUtils.getTrace();
        }
    }
}
